package com.mes.biz.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.ConvertRatioNumberUnit;
import com.mes.biz.mapper.BizInventoryOrderMapper;
import com.mes.biz.service.*;
import com.mes.common.constant.BizConstants;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.DateUtils;
import com.mes.common.utils.SecurityUtils;
import com.mes.system.strategy.AutoCodeUtil;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 盘点单Service业务层处理
 * @author wy
 * @email wy
 * @date 2023-06-19
 */
@Service
@Transactional(readOnly = true)
public class BizInventoryOrderServiceImpl extends BaseServiceImpl<BizInventoryOrderMapper, BizInventoryOrder> implements BizInventoryOrderService {

    private static final Logger log = LoggerFactory.getLogger(BizInventoryOrderServiceImpl.class);

    @Resource
    private AutoCodeUtil autoCodeUtil;

    @Resource
    private BizInventoryOrderDetailService bizInventoryOrderDetailService;

    @Resource
    private BizProductInventoryService bizProductInventoryService;

    @Resource
    private BizProductService bizProductService;

    @Resource
    private BizProductInventoryBookService bizProductInventoryBookService;

    @Resource
    private BizWarehouseService bizWarehouseService;

    /**
     * 获取单条数据
     * @param bizInventoryOrder 盘点单
     * @return 盘点单
     */
    @Override
    public BizInventoryOrder get(BizInventoryOrder bizInventoryOrder) {
        BizInventoryOrder dto = super.get(bizInventoryOrder);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 盘点单id
     * @return 盘点单
     */
    @Override
    public BizInventoryOrder get(String id) {
        BizInventoryOrder dto = super.get(id);
        return dto;
    }

    /**
     * 查询盘点单列表
     * @param bizInventoryOrder 盘点单
     * @return 盘点单
     */
    @Override
    public List<BizInventoryOrder> findList(BizInventoryOrder bizInventoryOrder) {
		List<BizInventoryOrder> bizInventoryOrderList = super.findList(bizInventoryOrder);
        for (BizInventoryOrder inventoryOrder : bizInventoryOrderList) {
            BizWarehouse bizWarehouse = bizWarehouseService.get(inventoryOrder.getWarehouseId());
            bizWarehouse.setWarehouseName(bizWarehouse.getWarehouseName());
        }

        return bizInventoryOrderList;
    }

    /**
     * 分页查询盘点单列表
     * @param bizInventoryOrder 盘点单
     * @return 盘点单
     */
    @Override
    public PageInfo<BizInventoryOrder> findPage(BizInventoryOrder bizInventoryOrder) {
		PageInfo<BizInventoryOrder> page = super.findPage(bizInventoryOrder);
        return page;
    }

    /**
     * 保存盘点单
     * @param bizInventoryOrder
     * @return 结果
     */
    @Override
    public boolean save(BizInventoryOrder bizInventoryOrder) {
        return super.save(bizInventoryOrder);
    }

    /**
     * 删除盘点单信息
     * @param bizInventoryOrder
     * @return 结果
     */
    @Override
    public boolean remove(BizInventoryOrder bizInventoryOrder) {
        return super.remove(bizInventoryOrder);
    }

    /**
     * 批量删除盘点单
     * @param ids 需要删除的盘点单ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizInventoryOrderByIds(String[] ids) {
        return mapper.deleteBizInventoryOrderByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean insertBizInventoryOrder(BizInventoryOrder bizInventoryOrder) {
        String code = autoCodeUtil.genSerialCode("RECEIVE_ORDER_CODE",null);
        bizInventoryOrder.setInventoryCode(code);
        String tenantId = SecurityUtils.getTenantId();
        bizInventoryOrder.setTenantId(tenantId);
        bizInventoryOrder.setStatus("1");
        boolean res = save(bizInventoryOrder);
        if(res) {
            for (BizInventoryOrderDetail details : bizInventoryOrder.getDetailList()) {
                BizInventoryOrderDetail bizInventoryOrderDetail = new BizInventoryOrderDetail();
                bizInventoryOrderDetail.setProductCode(details.getProductCode());
                bizInventoryOrderDetail.setUnit(details.getUnit());
                bizInventoryOrderDetail.setSpaceId(details.getSpaceId());
                bizInventoryOrderDetail.setNumber(details.getNumber());
                bizInventoryOrderDetail.setStock(details.getStock());
                bizInventoryOrderDetail.setTenantId(tenantId);
                bizInventoryOrderDetail.setRemark(details.getRemark());
                bizInventoryOrderDetail.setInventoryOrderId(bizInventoryOrder.getId());
                bizInventoryOrderDetailService.save(bizInventoryOrderDetail);
            }
        }
        return res;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean updateBizInventoryOrder(BizInventoryOrder bizInventoryOrder) {
        boolean res = save(bizInventoryOrder);
        if( bizInventoryOrder.getDetailList().size()>0) {
            String tenantId = SecurityUtils.getTenantId();
            bizInventoryOrderDetailService.deleteBizInventoryOrderDetailByInventoryOrderId(bizInventoryOrder.getId());
            for (BizInventoryOrderDetail details : bizInventoryOrder.getDetailList()) {
                BizInventoryOrderDetail bizInventoryOrderDetail = new BizInventoryOrderDetail();
                bizInventoryOrderDetail.setProductCode(details.getProductCode());
                bizInventoryOrderDetail.setUnit(details.getUnit());
                bizInventoryOrderDetail.setSpaceId(details.getSpaceId());
                bizInventoryOrderDetail.setNumber(details.getNumber());
                bizInventoryOrderDetail.setStock(details.getStock());
                bizInventoryOrderDetail.setTenantId(tenantId);
                bizInventoryOrderDetail.setRemark(details.getRemark());
                bizInventoryOrderDetail.setInventoryOrderId(bizInventoryOrder.getId());
                bizInventoryOrderDetailService.save(bizInventoryOrderDetail);
            }
        }
        return res;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean auditBizInventoryOrder(String id) {
        BizInventoryOrder bizInventoryOrder = super.get(id);
        bizInventoryOrder.setStatus("2");
        mapper.update(bizInventoryOrder);
        BizInventoryOrderDetail paramDetail = new BizInventoryOrderDetail();
        paramDetail.setInventoryOrderId(bizInventoryOrder.getId());
        List<BizInventoryOrderDetail> list = bizInventoryOrderDetailService.findList(paramDetail);
        for(BizInventoryOrderDetail details:list) {
//            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductId(details.getProductCode());
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
            BizProductInventory bizProductInventory = new BizProductInventory();
            bizProductInventory.setWarehouseId(bizInventoryOrder.getWarehouseId());
            bizProductInventory.setSpaceId(details.getSpaceId());
            bizProductInventory.setProductId(bizProduct.getId());
            BizProductInventory inventoryList = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),details.getSpaceId());
            BigDecimal qua = BigDecimal.ZERO;
            if (details.getNumber() ==null ){
                throw new BizException("审核时，盘点数量不能为空");
            }
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getNumber(), details.getUnit(), bizProduct);
            if(inventoryList==null) {
                inventoryList = new BizProductInventory();
                inventoryList.setProductId(bizProduct.getId());
                inventoryList.setAmount(BigDecimal.ZERO);
                inventoryList.setNumber(basicNumber);
                inventoryList.setPrice(BigDecimal.ZERO);
                inventoryList.setSpaceId(details.getSpaceId());
                inventoryList.setWarehouseId(bizInventoryOrder.getWarehouseId());
                inventoryList.setTenantId(SecurityUtils.getTenantId());
                inventoryList.setAssistNumberA(inventoryList.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                inventoryList.setAssistNumberB(inventoryList.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventoryService.save(inventoryList);
            } else {
                if (inventoryList.getNumber() !=null){
                    qua = basicNumber.subtract(inventoryList.getNumber());
                }else {
                    qua = basicNumber;
                }
                inventoryList.setProductId(bizProduct.getId());
                inventoryList.setNumber(basicNumber);
                inventoryList.setAssistNumberA(inventoryList.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                inventoryList.setAssistNumberB(inventoryList.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventoryService.update(inventoryList);
            }
            //保存产品库存台账
            BizProductInventoryBook productInventoryBook = new BizProductInventoryBook();
            productInventoryBook.setBizDate(DateUtils.getNowDate());
            productInventoryBook.setAmount(BigDecimal.ZERO);
            productInventoryBook.setAssistUnitA(inventoryList.getAssistUnitA());
            productInventoryBook.setAssistUnitB(inventoryList.getAssistUnitB());
            productInventoryBook.setSpaceId(details.getSpaceId());
            productInventoryBook.setWarehouseId(bizInventoryOrder.getWarehouseId());
            productInventoryBook.setInventoryId(inventoryList.getId());
            productInventoryBook.setNumber(qua);
            productInventoryBook.setAssistNumberB(qua.multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setAssistNumberA(qua.multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setOrderNumber(bizInventoryOrder.getInventoryCode());
            productInventoryBook.setOrderType(BizConstants.ORDER_TYPE_INVENTORY);
            productInventoryBook.setPrice(BigDecimal.ZERO);
            productInventoryBook.setProductModel(bizProduct.getModel());
            productInventoryBook.setTenantId(SecurityUtils.getTenantId());
            productInventoryBook.setProductId(bizProduct.getId());
            productInventoryBook.setRemark(bizInventoryOrder.getRemark());
            productInventoryBook.setOrderType("4");
            bizProductInventoryBookService.save(productInventoryBook);
        }
        return true;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean doAuditBizInventoryOrder(String id) {
        BizInventoryOrder bizInventoryOrder = super.get(id);
        bizInventoryOrder.setStatus("1");
        mapper.update(bizInventoryOrder);
        BizInventoryOrderDetail paramDetail = new BizInventoryOrderDetail();
        paramDetail.setInventoryOrderId(bizInventoryOrder.getId());
        List<BizInventoryOrderDetail> list = bizInventoryOrderDetailService.findList(paramDetail);
        for(BizInventoryOrderDetail details:list) {
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
            BizProductInventoryBook bizProductInventoryBook = bizProductInventoryBookService.
                    selectBizProductInventoryBookByOrderNumber(bizInventoryOrder.getInventoryCode(),details.getSpaceId(),bizProduct.getId());
            BizProductInventory bizProductInventory = new BizProductInventory();
            bizProductInventory.setWarehouseId(bizInventoryOrder.getWarehouseId());
            bizProductInventory.setSpaceId(details.getSpaceId());
            bizProductInventory.setProductId(bizProduct.getId());
            BizProductInventory inventoryList = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),details.getSpaceId());
            if(inventoryList!=null){
                if (inventoryList.getNumber()!=null){
                    inventoryList.setNumber(inventoryList.getNumber().subtract(bizProductInventoryBook.getNumber()));
                }else {
                    inventoryList.setNumber(bizProductInventoryBook.getNumber());
                }
                inventoryList.setAssistNumberA(inventoryList.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                inventoryList.setAssistNumberB(inventoryList.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventoryService.update(inventoryList);
            }
        }
        //删除产品库存台账
        bizProductInventoryBookService.deleteBizProductInventoryBookByOrderNumber(bizInventoryOrder.getInventoryCode());
        return true;
    }

}
